package com.tcjk.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class StringUtil {

	/**
	 * 比较两个byte数组数据是否相同,相同返回 true
	 * 
	 * @param data1
	 * @param data2
	 * @param len
	 * @return
	 */
	public static boolean equalsByte(byte[] data1, byte[] data2, int len) {
		if (data1 == null && data2 == null) {
			return true;
		}
		if (data1 == null || data2 == null) {
			return false;
		}
		if (data1 == data2) {
			return true;
		}
		boolean bEquals = true;
		int i;
		for (i = 0; i < data1.length && i < data2.length && i < len; i++) {
			if (data1[i] != data2[i]) {
				bEquals = false;
				break;
			}
		}
		return bEquals;
	}

	/***
	 * 压缩GZip
	 * 
	 * @param data
	 * @return
	 */
	public static byte[] gZip(byte[] data) {
		byte[] b = null;
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			GZIPOutputStream gzip = new GZIPOutputStream(bos);
			gzip.write(data);
			gzip.finish();
			gzip.close();
			b = bos.toByteArray();
			bos.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return b;
	}

	/***
	 * 解压GZip
	 * 
	 * @param data
	 * @return
	 */
	public static byte[] unGZip(byte[] data) {
		byte[] b = null;
		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(data);
			GZIPInputStream gzip = new GZIPInputStream(bis);
			byte[] buf = new byte[1024];
			int num = -1;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while ((num = gzip.read(buf, 0, buf.length)) != -1) {
				baos.write(buf, 0, num);
			}
			b = baos.toByteArray();
			baos.flush();
			baos.close();
			gzip.close();
			bis.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return b;
	}

	/**
	 * Get XML String of utf-8
	 * 
	 * @return XML-Formed string
	 */
	public static Map<Integer, String> tokenMap = new HashMap<Integer, String>();

	public static String getUTF8XMLString(String xml) {
		// A StringBuffer Object
		StringBuffer sb = new StringBuffer();
		sb.append(xml);
		String xmString = "";
		String xmlUTF8 = "";
		try {
			xmString = new String(sb.toString().getBytes("UTF-8"));
			xmlUTF8 = URLEncoder.encode(xmString, "UTF-8");
			System.out.println("utf-8 编码：" + xmlUTF8);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// return to String Formed
		return xmlUTF8;
	}

	public static String[] splitString(String sInput, String sDelimiter) {
		if (StringUtil.checkNull(sInput)) {
			return null;
		}
		StringTokenizer st = new StringTokenizer(sInput, sDelimiter);
		int size = st.countTokens();
		// System.out.println("size="+size);
		String output[] = new String[size];
		for (int i = 0; i < size; i++) {
			output[i] = st.nextToken();
		}
		return output;
	}

	static int flowNum = 0;

	public static String getNewFlowNum() {
		if (flowNum >= 99999999) {
			flowNum = 0;
		}
		flowNum = flowNum + 1;
		String str = String.valueOf(flowNum);
		while (str.length() < 8) {
			str = "0" + str;
		}
		return str;
	}

	public static String getNewflowcode(String prefix) {
		String flowcode = prefix + StringUtil.timeToString(new Date(), "yyyyMMddHHmmss")
				+ StringUtil.getNewFlowNum();
		return flowcode;
	}

	public static String getNewToken() {
		String str1 = Long.toString(Long.valueOf(StringUtil.timeToString(new Date(), "yyyyMMddHHmmss")), 36);
		String str2 = Long.toString(Long.valueOf(StringUtil.getNewFlowNum()),36).toString();
		return str1+str2;
	}
	
	public static synchronized String getNewToken2(String prefix) {
		long currentTime = System.currentTimeMillis();
	//	System.out.println("currentTime="+currentTime);
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return prefix+CompressEncodeing.compressNumber(currentTime,6);
	}
	
	public static String getShortflowcode() {

		long code = System.currentTimeMillis();
		return Long.toHexString(code);
	}

	public static boolean checkNull(String sInput) {
		boolean flag = false;
		try {
			// System.out.println("aaaaaaaaaa");
			if ("".equals(sInput) || null == sInput || "null".equals(sInput)) {
				// System.out.println("bbbbbbbbbbbbb");
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// System.out.println("cccccccccccccc");
		return flag;
	}

	public static Date StringTotime(String format) {
		try {
			if (checkNull(format)) {
				return null;
			}
			SimpleDateFormat localTime = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			Date d = localTime.parse(format);
			return d;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Date StringTotime(String str, String format) {
		try {
			if (checkNull(str)) {
				return null;
			}
			SimpleDateFormat localTime = new SimpleDateFormat(format);
			Date d = localTime.parse(str);
			return d;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String timeToString(java.util.Date d, String format) {
		SimpleDateFormat localTime = new SimpleDateFormat(format);
		String date = localTime.format(d);
		return date;
	}

	public static String timeToString(java.sql.Timestamp d, String format) {
		SimpleDateFormat localTime = new SimpleDateFormat(format);
		String date = localTime.format(d);
		return date;
	}

	/**
	 * 时间戳转换为字符串
	 * 
	 * @param time
	 * @return
	 */
	public static String timestamp2Str(Timestamp time, String format) {
		Date date = null;
		if (null != time) {
			date = new Date(time.getTime());
		}
		return timeToString(date, format);
	}

	// 将 UTF-8 编码的字符串转换为 GB2312 编码格式：F
	public static String utf8Togb2312(String str) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			switch (c) {
			case '+':
				sb.append(' ');
				break;
			case '%':
				try {
					sb.append((char) Integer.parseInt(
							str.substring(i + 1, i + 3), 16));
				} catch (NumberFormatException e) {
					throw new IllegalArgumentException();
				}
				i += 2;
				break;
			default:
				sb.append(c);
				break;
			}
		}
		String result = sb.toString();
		String res = null;
		try {
			byte[] inputBytes = result.getBytes("8859_1");
			res = new String(inputBytes, "UTF-8");
		} catch (Exception e) {
		}
		return res;
	}

	public static String getTime(String time) {
		String date = "";
		if (!StringUtil.checkNull(time)) {
			if (time.length() > 10) {
				date = time.substring(0, 10);
			}
		}
		return date;
	}

	// 将 GB2312 编码格式的字符串转换为 UTF-8 格式的字符串：
	public static String gb2312ToUtf8(String str) {
		String urlEncode = "";
		try {
			urlEncode = URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return urlEncode;
	}

	/**
	 * 生成随机密码
	 * 
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length, String pw) {
		StringBuffer buffer = new StringBuffer(pw);
		StringBuffer sb = new StringBuffer();
		java.util.Random r = new java.util.Random();
		int range = buffer.length();
		for (int i = 0; i < length; i++) {
			sb.append(buffer.charAt(r.nextInt(range)));
		}
		return sb.toString();
	}

	/**
	 * 保存文件
	 * 
	 * @param path
	 * @param file
	 * @param filename
	 * @return
	 */
	public static int savefiles(String path, File file, String filename) {
		int result = 0;
		try {
			java.io.InputStream is = new java.io.FileInputStream(file);
			// 判断文件夹是否存在
			File f = new File(path);
			if (!f.exists() && !f.isDirectory()) {
				f.mkdirs();
			}
			java.io.OutputStream os = new java.io.FileOutputStream(path
					+ File.separator + filename);
			byte buffer[] = new byte[8192];
			int count = 0;
			while ((count = is.read(buffer)) > 0) {
				os.write(buffer, 0, count);
			}
			os.close();
			is.close();
			result = 1;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 返回微信的全局返回码对应的说明
	 * 
	 * @param code
	 * @return
	 */
	public static String getDetial(String code) {
		String detial = null;
		if ("9001036".equals(code)) {
			detial = "查询起始值begin不合法";

		} else if ("9001035".equals(code)) {
			detial = "设备申请参数不合法";

		} else if ("9001034".equals(code)) {
			detial = "设备备注信息过长";

		} else if ("9001033".equals(code)) {
			detial = "门店ID不合法";

		} else if ("9001032".equals(code)) {
			detial = "保存设备与页面的绑定关系参数错误";

		} else if ("9001031".equals(code)) {
			detial = "时间区间不合法";

		} else if ("9001030".equals(code)) {
			detial = "一次查询页面ID数量不能超过50";

		} else if ("9001029".equals(code)) {
			detial = "页面已应用在设备中，请先解除应用关系再删除";

		} else if ("9001028".equals(code)) {
			detial = "一次删除页面ID数量不能超过10";

		} else if ("9001027".equals(code)) {
			detial = "页面参数不合法";

		} else if ("9001026".equals(code)) {
			detial = "页面ID不合法";

		} else if ("9001025".equals(code)) {
			detial = "设备ID不合法";

		} else if ("9001024".equals(code)) {
			detial = "一次查询设备ID数量不能超过50";

		} else if ("9001023".equals(code)) {
			detial = "已存在审核中的设备ID申请";

		} else if ("9001022".equals(code)) {
			detial = "设备申请数不合法，必须为大于0的数字";

		} else if ("9001021".equals(code)) {
			detial = "已有设备激活率低于50%，不能新增设备";

		} else if ("9001020".equals(code)) {
			detial = "帐号不合法";

		} else if ("9001010".equals(code)) {
			detial = "上传失败";

		} else if ("9001009".equals(code)) {
			detial = "上传素材的文件尺寸不合法";

		} else if ("9001008".equals(code)) {
			detial = "上传素材的文件类型不合法";

		} else if ("9001007".equals(code)) {
			detial = "上传文件缺失";

		} else if ("9001006".equals(code)) {
			detial = "获取OpenID失败";

		} else if ("9001005".equals(code)) {
			detial = "获取商户信息失败";

		} else if ("9001004".equals(code)) {
			detial = "获取摇周边用户信息失败";

		} else if ("9001003".equals(code)) {
			detial = "Ticket不合法";

		} else if ("9001002".equals(code)) {
			detial = "远端服务不可用";

		} else if ("9001001".equals(code)) {
			detial = "POST数据参数不合法";

		} else if ("61501".equals(code)) {
			detial = "日期范围错误";

		} else if ("61500".equals(code)) {
			detial = "日期格式错误";

		} else if ("61450".equals(code)) {
			detial = "系统错误(system error)";

		} else if ("61457".equals(code)) {
			detial = "无效头像文件类型(invalid file type)";

		} else if ("61456".equals(code)) {
			detial = "客服帐号个数超过限制(10个客服账号)(kf_account count exceeded)";

		} else if ("61455".equals(code)) {
			detial = "客服帐号名包含非法字符(仅允许英文+数字)(illegal character in kf_account)";

		} else if ("61454".equals(code)) {
			detial = "客服帐号名长度超过限制(仅允许10个英文字符，不包括@及@后的公众号的微信号)(invalid kf_acount length)";

		} else if ("61453".equals(code)) {
			detial = "客服帐号已存在(kf_account exsited)";

		} else if ("61452".equals(code)) {
			detial = "无效客服账号(invalid kf_account)";

		} else if ("61451".equals(code)) {
			detial = "参数错误(invalid parameter)";

		} else if ("50002".equals(code)) {
			detial = "用户受限，可能是违规后接口被封禁";

		} else if ("50001".equals(code)) {
			detial = "用户未授权该api";

		} else if ("-1".equals(code)) {
			detial = "系统繁忙，此时请开发者稍候再试";

		} else if ("0".equals(code)) {
			detial = "请求成功";

		} else if ("40001".equals(code)) {
			detial = "获取access_token时AppSecret错误，或者access_token无效。请开发者认真比对AppSecret的正确性，或查看是否正在为恰当的公众号调用接口";

		} else if ("40002".equals(code)) {
			detial = "不合法的凭证类型";

		} else if ("40003".equals(code)) {
			detial = "不合法的OpenID，请开发者确认OpenID（该用户）是否已关注公众号，或是否是其他公众号的OpenID";

		} else if ("40004".equals(code)) {
			detial = "不合法的媒体文件类型";

		} else if ("40005".equals(code)) {
			detial = "不合法的文件类型";

		} else if ("40004".equals(code)) {
			detial = "不合法的文件大小";

		} else if ("40007".equals(code)) {
			detial = "不合法的媒体文件id";

		} else if ("40008".equals(code)) {
			detial = "不合法的消息类型";

		} else if ("40009".equals(code)) {
			detial = "不合法的图片文件大小";

		} else if ("40010".equals(code)) {
			detial = "不合法的语音文件大小";

		} else if ("40011".equals(code)) {
			detial = "不合法的视频文件大小";

		} else if ("40012".equals(code)) {
			detial = "不合法的缩略图文件大小";

		} else if ("40013".equals(code)) {
			detial = "不合法的AppID，请开发者检查AppID的正确性，避免异常字符，注意大小写";

		} else if ("40014".equals(code)) {
			detial = "不合法的access_token，请开发者认真比对access_token的有效性（如是否过期），或查看是否正在为恰当的公众号调用接口";

		} else if ("40015".equals(code)) {
			detial = "不合法的菜单类型";

		} else if ("40016".equals(code)) {
			detial = "不合法的按钮个数";

		} else if ("40017".equals(code)) {
			detial = "不合法的按钮个数";

		} else if ("40018".equals(code)) {
			detial = "不合法的按钮名字长度";

		} else if ("40019".equals(code)) {
			detial = "不合法的按钮KEY长度";

		} else if ("40020".equals(code)) {
			detial = "不合法的按钮URL长度";

		} else if ("40021".equals(code)) {
			detial = "不合法的菜单版本号";

		} else if ("40022".equals(code)) {
			detial = "不合法的子菜单级数";

		} else if ("40023".equals(code)) {
			detial = "不合法的子菜单按钮个数";

		} else if ("40024".equals(code)) {
			detial = "不合法的子菜单按钮类型";

		} else if ("40025".equals(code)) {
			detial = "不合法的子菜单按钮名字长度";

		} else if ("40026".equals(code)) {
			detial = "不合法的子菜单按钮KEY长度";

		} else if ("40027".equals(code)) {
			detial = "不合法的子菜单按钮URL长度";

		} else if ("40028".equals(code)) {
			detial = "不合法的自定义菜单使用用户";

		} else if ("40029".equals(code)) {
			detial = "不合法的oauth_code";

		} else if ("40030".equals(code)) {
			detial = "不合法的refresh_token";

		} else if ("40031".equals(code)) {
			detial = "不合法的openid列表";

		} else if ("40032".equals(code)) {
			detial = "不合法的openid列表长度";

		} else if ("40033".equals(code)) {
			detial = "不合法的请求字符，不能包含+" + "'\'" + "uxxxx格式的字符";

		} else if ("40035".equals(code)) {
			detial = "不合法的参数";

		} else if ("40038".equals(code)) {
			detial = "不合法的请求格式";

		} else if ("40039".equals(code)) {
			detial = "不合法的URL长度";

		} else if ("40050".equals(code)) {
			detial = "不合法的分组id";

		} else if ("40051".equals(code)) {
			detial = "分组名字不合法";

		} else if ("40117".equals(code)) {
			detial = "分组名字不合法";

		} else if ("40118".equals(code)) {
			detial = "media_id大小不合法";

		} else if ("40119".equals(code)) {
			detial = "button类型错误";

		} else if ("40120".equals(code)) {
			detial = "button类型错误";

		} else if ("40121".equals(code)) {
			detial = "不合法的media_id类型";

		} else if ("40132".equals(code)) {
			detial = "微信号不合法";

		} else if ("40137".equals(code)) {
			detial = "不支持的图片格式";

		} else if ("41001".equals(code)) {
			detial = "缺少access_token参数";

		} else if ("41002".equals(code)) {
			detial = "缺少appid参数";

		} else if ("41003".equals(code)) {
			detial = "缺少refresh_token参数";

		} else if ("41004".equals(code)) {
			detial = "缺少secret参数";

		} else if ("41005".equals(code)) {
			detial = "缺少多媒体文件数据";

		} else if ("41006".equals(code)) {
			detial = "缺少media_id参数";

		} else if ("41007".equals(code)) {
			detial = "缺少子菜单数据";

		} else if ("41008".equals(code)) {
			detial = "缺少oauth code";

		} else if ("41009".equals(code)) {
			detial = "缺少openid";

		} else if ("42001".equals(code)) {
			detial = "access_token超时，请检查access_token的有效期，请参考基础支持-获取";

		} else if ("42001".equals(code)) {
			detial = "access_token超时，请检查access_token的有效期，请参考基础支持-获取access_token中，对access_token的详细机制说明";

		} else if ("42002".equals(code)) {
			detial = "refresh_token超时";

		} else if ("42003".equals(code)) {
			detial = "oauth_code超时";

		} else if ("43001".equals(code)) {
			detial = "需要GET请求";

		} else if ("43002".equals(code)) {
			detial = "需要POST请求";

		} else if ("43003".equals(code)) {
			detial = "需要HTTPS请求";

		} else if ("43004".equals(code)) {
			detial = "需要接收者关注";

		} else if ("43005".equals(code)) {
			detial = "需要好友关系";

		} else if ("44001".equals(code)) {
			detial = "多媒体文件为空";

		} else if ("44002".equals(code)) {
			detial = "POST的数据包为空";

		} else if ("44003".equals(code)) {
			detial = "图文消息内容为空";

		} else if ("44004".equals(code)) {
			detial = "文本消息内容为空";

		} else if ("45001".equals(code)) {
			detial = "多媒体文件大小超过限制";

		} else if ("45002".equals(code)) {
			detial = "消息内容超过限制";

		} else if ("45003".equals(code)) {
			detial = "标题字段超过限制";

		} else if ("45004".equals(code)) {
			detial = "描述字段超过限制";

		} else if ("45005".equals(code)) {
			detial = "链接字段超过限制";

		} else if ("45006".equals(code)) {
			detial = "图片链接字段超过限制";

		} else if ("45007".equals(code)) {
			detial = "语音播放时间超过限制";

		} else if ("45008".equals(code)) {
			detial = "图文消息超过限制";

		} else if ("45009".equals(code)) {
			detial = "接口调用超过限制";

		} else if ("45010".equals(code)) {
			detial = "创建菜单个数超过限制";

		} else if ("45015".equals(code)) {
			detial = "回复时间超过限制";

		} else if ("45016".equals(code)) {
			detial = "系统分组，不允许修改";

		} else if ("45017".equals(code)) {
			detial = "分组名字过长";

		} else if ("45018".equals(code)) {
			detial = "分组数量超过上限";

		} else if ("46001".equals(code)) {
			detial = "不存在媒体数据";

		} else if ("46002".equals(code)) {
			detial = "不存在的菜单版本";

		} else if ("46003".equals(code)) {
			detial = "不存在的菜单数据";

		} else if ("46004".equals(code)) {
			detial = "不存在的用户";

		} else if ("47001".equals(code)) {
			detial = "解析JSON/XML内容错误";

		} else if ("48001".equals(code)) {
			detial = "api功能未授权，请确认公众号已获得该接口，可以在公众平台官网-开发者中心";

		}
		return detial;
	}
	
	public static int flowId = 0;
	public static byte[] getNewFlowID(){
		if (flowId >= 16384) {
			flowId = 0;
		}
		flowId = flowId + 1;
		byte[] byt = new byte[2];
		byte[] bbb = TypeConversion.intToBytes2(flowId);
		byt[0] = bbb[2];
		byt[1] = bbb[3];
		System.out.println("bbb[0]"+bbb[0]);
		System.out.println("bbb[1]"+bbb[1]);
		System.out.println("bbb[2]"+bbb[2]);
		System.out.println("bbb[3]"+bbb[3]);
		return byt;
	}
	
	public  static void main(String args[]){
//		String ss = getNewToken2("H");
//		System.out.println("ss="+ss);
//		long aa = CompressEncodeing.UnCompressNumber(ss.substring(1));
//		System.out.println("aa="+aa);
//		flowId = 16383;
//		byte byt[] = getNewFlowID();
//		byte ccc[] = new byte[4];
//		ccc[0] = 0;
//		ccc[1] = 0;
//		ccc[2] = byt[0];
//		ccc[3] = byt[1];
//		int t = TypeConversion.bytesToInt2(ccc, 0);
//		System.out.println("ccc[2]="+ccc[2]);
//		System.out.println("ccc[3]="+ccc[3]);
//		System.out.println("t="+t);
		
	    for(int i=0;i<10000;i++){
			String flowcode = getNewflowcode("A");
			System.out.println(flowcode);
	    }
	}
}